package com.itheima.reggie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.Pojo.Employee;
import com.itheima.reggie.Service.EmployeeService;
import com.itheima.reggie.Service.impl.EmployeeServiceImpl;
import com.itheima.reggie.common.R;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService service;

    /**
     * 员工登录
     * 设置HTTPServletRequest对象是为了获取存储到Session域里的运行结果
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

//     1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

//     2、根据页面提交的同户名username查询数据库
        LambdaQueryWrapper<Employee> query = new LambdaQueryWrapper<>();
        query.eq(Employee::getUsername, employee.getUsername());
        Employee one = service.getOne(query);

//     3、如果没有查询到则返回登录失败结果
        if(one==null){
            return R.error("登录失败");
        }

//     4、密码比对，如果不一致则返回登录失败结果
        if(!one.getPassword().equals(password)){
            return R.error("登录失败");
        }

//     5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(one.getStatus()==0){
            return R.error("账号已禁用");
        }

//     6、登录成功，将员工id存入到Session并返回登录成功结果
        request.getSession().setAttribute("Employee",one.getId());
        return R.success(one);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */

    @PostMapping("/logout")
    public R<String> remove(HttpServletRequest request){
//      移除Session中保存的数据，跳转回登录页面由前端负责
        request.getSession().removeAttribute("Employee");
        return R.success("退出成功");
    }


    /**
     * 新增员工
     * @param employee
     * @return
     */

    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
//      1、添加初始密码，进行MD5加密，需要转为字节数组类型
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//      2、设置创建时间和修改时间，取当前时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//      3、设置创建人和最后修改人，取当前登录的用户的id作为其值，需要转为long型
//        employee.setCreateUser((long)request.getSession().getAttribute("Employee"));
//        employee.setUpdateUser((long)request.getSession().getAttribute("Employee"));
//      id、status有默认值，不需要我们添加

//      4、将数据添加到数据库
        service.save(employee);
        return R.success("添加用户成功");
    }


    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page={} pageSize={} name={}",page,pageSize,name);
//      构造分页构造器
        Page pageInfo=new Page(page,pageSize);
//      构造条件构造器(条件对象)
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper();
//      添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
//      添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
//      执行分页查询(放入分页对象跟条件)
        service.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }


    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
//        Long userid = (Long)request.getSession().getAttribute("Employee");
//
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(userid);
        service.updateById(employee);
        return R.success("修改成功");
    }

    /**
     *  根据id查员工数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> queryid(@PathVariable Long id){
        log.info("根据id查员工数据----");
        Employee employee = service.getById(id);
        if(employee!=null){
            return R.success(employee);
        }
        return R.error("用户不存在");

    }
}
